package com.zwb.aiwebsite.controller;

import com.zwb.aiwebsite.common.ResponseResult;
import com.zwb.aiwebsite.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 通用控制器
 * 管理一些文件上传什么的
 *
 *
 * @author 2825075112@qq.com
 */
@Controller
public class CommonController {

    @Value("${common.upload-path}")
    private String uploadPath ;

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public ResponseResult<String> uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = uploadPath;
            File uploadDir = ResourceUtils.getFile(filePath);
            if (!uploadDir.exists()){
                uploadDir.mkdirs();
            }
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(uploadDir.getAbsolutePath(), file);
            System.out.println(fileName);
            return ResponseResult.okOf(fileName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }
}
